package wsem.model;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;









import wsem.result.ResultSearch;
import wsem.utils.ConfigUtils;

public class QueriesJDBC {
	
	private static String URL = ConfigUtils.URL_BD;
	private static String LOGIN = ConfigUtils.USER_BD;
	private static String PASSWORD = "";
	private PreparedStatement preparedStatement = null;
	
	public LinkedList<ResultSearch> findDocumentIfExistTerm(String motcle,String xpath,String nomDoc) throws SQLException {
		
		LinkedList<ResultSearch> mapDoc = new LinkedList<ResultSearch>();
		
		Connection con = null;
		
		Statement stmt  = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e1) {

			e1.printStackTrace();
		}
		try {
			con = DriverManager.getConnection(URL, LOGIN, PASSWORD);

			stmt = con.createStatement();
	
			preparedStatement = con
					.prepareStatement("SELECT poids, term, xpath , nomDoc FROM  `ws_db`.`doc` ,"
							+ "`ws_db`.`noeud`,  `ws_db`.`term_noeud` ,  `ws_db`.`term` "+ 
							"WHERE `doc`.`idDoc` = `noeud`.`idDoc` "
							+ "AND `term_noeud`.`idTerm` = `term`.`idTerm` "
							+ "AND `term_noeud`.`idNoeud` = `noeud`.`idNoeud` "
							+ "AND term= ? "
							+ "AND xpath=?"
							+ "ORDER BY poids DESC");
			preparedStatement.setString(1, motcle);
			
			preparedStatement.setString(2, xpath.substring(1, xpath.length()));
			
			ResultSet rset = preparedStatement.executeQuery();

			while (rset.next()) {
				ResultSearch res = new ResultSearch();
				String termCurrent = rset.getString("term");
				res.setTerm(termCurrent);
				res.setPoid(rset.getDouble("poids"));
				
				
				res.setXpath(rset.getString("xpath"));
				mapDoc.add(res);
				
				
 
			}
 
		} catch (SQLException e) {
 
			System.out.println(e.getMessage());
 
		} finally {
 
			if (stmt != null) {
				stmt.close();
			}
 
			if (con != null) {
				con.close();
			}
 
		}
			


		return mapDoc;

	}
	
	public static void main(String[] args) {
		
		QueriesJDBC indexDao = new QueriesJDBC();
		try {
			indexDao.findDocumentIfExistTerm("Mont","/BALADE[1]/RECIT[1]/SEC[12]/P[2]","d101.xml");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	

}
